package com.atguigu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassName: CategoryExcelListener
 * Package: com.atguigu.spzx.manager.listener
 * Description:
 *
 * @Author 刘强
 * @Create 2024/7/5 9:52
 * @Version 1.0
 */
public class CategoryExcelListener<T> extends AnalysisEventListener<T>{
    // 缓冲区的大小，满了后就添加到数据库
    private final Integer BUFFER_SIZE = 100;
    private List<CategoryExcelVo> categoryExcelVos = new ArrayList<>(BUFFER_SIZE);
    // 注意：EasyExcel的监听器不能被ioc管理。
    private CategoryMapper categoryMapper;

    public CategoryExcelListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    /**
     * EasyExcel读取一行数据执行一次 但我们要实现批量插入
     * @param t
     * @param analysisContext
     */
    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        categoryExcelVos.add((CategoryExcelVo) t);
        if(categoryExcelVos.size() >= BUFFER_SIZE){
//            向数据库中添加
            categoryMapper.insertBatch(categoryExcelVos);
            // 缓冲区满了，清空缓冲区
            categoryExcelVos = new ArrayList<>(BUFFER_SIZE);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 刷新缓冲区 ---> 缓冲区有残留数据
        if(categoryExcelVos.size() != 0){
            categoryMapper.insertBatch(categoryExcelVos);
        }
    }
}
